package sim.core.handler;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import sim.core.annotation.Uri;

/**
 * Url映射类
 * 
 * @author Feny
 * @email 1220301855@qq.com
 * @version 1.0
 * @date 2018年7月30日下午1:56:16
 */
public class UrlHandler {

	private Map<String, ControllerHandler> urlMap = new LinkedHashMap<>();

	public void setMapping(String url, ControllerHandler controller) {
		urlMap.put(url, controller);
	}

	public ControllerHandler getController(String url) {
		return urlMap.get(url);
	}

	public static UrlHandler setUrlMapping(List<Class<?>> clazzs, Class<? extends Annotation> annotation) {
		UrlHandler mapping = new UrlHandler();

		// 解析方法上的注解
		for (Class<?> clazz : clazzs) {
			boolean classHasAnno = clazz.isAnnotationPresent(annotation);
			Method[] methods = clazz.getDeclaredMethods();
			for (Method method : methods) {
				boolean methodHasAnno = method.isAnnotationPresent(annotation);
				if (methodHasAnno) {
					// 得到注解
					Uri ann = method.getAnnotation(Uri.class);
					// 输出注解属性,uri.value();
					ControllerHandler controller = new ControllerHandler(clazz, method, ann.method());
					String uri = classHasAnno ? clazz.getAnnotation(Uri.class).value() : "";
					uri = "".equals(uri) || uri.startsWith("/") ? uri : "/" + uri;
					uri += ann.value().startsWith("/") ? ann.value() : "/" + ann.value();
					System.out.printf("UrlMaped：[%s] ---> %s.%s()\n", uri, clazz.getName(), method.getName());
					mapping.setMapping(uri, controller);
				}
			}
		}
		return mapping;
	}
}
